package org.seamon.management.sms;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.seamon.management.config.RabbitConfig;
import org.seamon.management.pojo.entity.SmsRecord;
import org.seamon.management.pojo.entity.SmsTask;
import org.seamon.management.service.SmsRecordService;
import org.seamon.management.service.SmsTaskService;
import org.seamon.management.util.RedissonUtil;
import org.seamon.management.util.enums.SmsStatusEnum;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static org.seamon.management.util.CacheConstants.SMS_LOCK_PREFIX;

/**
 * @author Simon
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SmsConsumer {

    @Resource
    private SmsRecordService smsRecordService;
    @Resource
    private SmsTaskService smsTaskService;
    @Resource
    private RedissonUtil redissonUtil;
    @Resource
    private SmsClient smsClient;

    @RabbitListener(queues = RabbitConfig.SMS_BATCH_QUEUE)
    public void processBatch(List<SmsTask> tasks) {
        if (tasks == null || tasks.isEmpty()) {
            return;
        }
        for (SmsTask task : tasks) {
            String lockKey = SMS_LOCK_PREFIX + task.getId();
            RLock lock = redissonUtil.getLock(lockKey);
            try {
                if (lock.tryLock()) {
                    log.info("开始处理任务，ID: {}", task.getId());
                    task.setStatus(SmsStatusEnum.TASK_PROCESSING.getCode());
                    smsTaskService.updateById(task);

                    sendBatchSms(Collections.singletonList(task));
                }
            } finally {
                lock.unlock();
            }
        }
    }


    /**
     * 使用阿里云 SDK 批量发送短信
     */
    private void sendBatchSms(List<SmsTask> batch) {
        List<String> phoneNumbers = new ArrayList<>();
        String signNames = "[\"阿里云短信测试\"]";
        String templateCode = "[\"SMS_323770490\"]";
        String templateParams = "{\"code\":\"" + batch.get(0).getContent() + "\"}";

        batch.forEach(task -> phoneNumbers.add(task.getPhone()));

        try {
            SendBatchSmsRequest request = new SendBatchSmsRequest();
            ObjectMapper mapper = new ObjectMapper();

            request.setPhoneNumberJson(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(phoneNumbers));
            request.setSignNameJson(signNames);
            request.setTemplateCode(templateCode);
            request.setTemplateParamJson(templateParams);

            Client client = smsClient.createClient();
            SendBatchSmsResponse response = client.sendBatchSms(request);
            log.info("发送短信响应结果：{}", response.getBody().getMessage());

            // 处理返回结果
            if ("OK".equals(response.getBody().getCode())) {
                for (SmsTask task : batch) {
                    SmsRecord record = new SmsRecord();
                    record.setTaskId(task.getId());
                    record.setPhone(task.getPhone());
                    record.setContent(task.getContent());
                    record.setStatus(SmsStatusEnum.RECORD_SUCCESS.getCode());
                    smsRecordService.save(record);

                    task.setStatus(SmsStatusEnum.TASK_SUCCESS.getCode());
                    smsTaskService.updateById(task);
                }
            } else {
                for (SmsTask task : batch) {
                    SmsRecord record = new SmsRecord();
                    record.setTaskId(task.getId());
                    record.setPhone(task.getPhone());
                    record.setContent(task.getContent());
                    record.setStatus(SmsStatusEnum.RECORD_FAIL.getCode());
                    record.setResponseCode(response.getBody().getCode());
                    record.setResponseMsg(response.getBody().getMessage());
                    smsRecordService.save(record);

                    task.setLastError(response.getBody().getMessage());
                    task.setRetryCount(task.getRetryCount() - 1);
                    if (task.getRetryCount() <= 0) {
                        task.setStatus(SmsStatusEnum.TASK_FAIL.getCode());
                    }
                    smsTaskService.updateById(task);
                }
            }

        } catch (Exception e) {
            // 其他异常处理
            log.error("发送短信异常：{}", e.getMessage());
            String errorMessage = e.getClass().getSimpleName();
            for (SmsTask task : batch) {
                SmsRecord record = new SmsRecord();
                record.setTaskId(task.getId());
                record.setPhone(task.getPhone());
                record.setContent(task.getContent());
                record.setStatus(SmsStatusEnum.RECORD_FAIL.getCode());
                smsRecordService.save(record);

                task.setLastError(errorMessage);
                task.setRetryCount(task.getRetryCount() - 1);
                if (task.getRetryCount() <= 0) {
                    task.setStatus(SmsStatusEnum.TASK_FAIL.getCode());
                }
                smsTaskService.updateById(task);
            }
        }
    }
}
